package com.liholin.springboot.sample.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liholin.springboot.sample.filter.HttpControllerAuthorizeFilter;
import com.liholin.springboot.sample.filter.HttpLogFilter;
import com.liholin.springboot.sample.service.AccessTokenService;
import com.liholin.springboot.sample.service.RedisService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.filter.GenericFilterBean;

@Configuration
@EnableScheduling
@EnableConfigurationProperties(value = {AppConfigProperties.class})
public class AppConfig {

    @Bean(name = "apiControllerFilterRegister")
    @ConditionalOnBean({AccessTokenService.class, RedisService.class})
    public FilterRegistrationBean apiControllerRegistrationFilter(AccessTokenService tokenService,
                                                                  AppConfigProperties properties,
                                                                  ObjectMapper objectMapper,
                                                                  RedisService redisService) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new HttpControllerAuthorizeFilter(properties, tokenService, objectMapper, redisService));
        registration.setName("HttpControllerAuthorizeFilter");
        registration.setOrder(Integer.MIN_VALUE);

        return registration;
    }

    @Bean
    public FilterRegistrationBean httpLogFilter(AppConfigProperties properties) {
        FilterRegistrationBean<GenericFilterBean> registration = new FilterRegistrationBean();
        HttpLogFilter httpLogFilter = new HttpLogFilter(properties);
        registration.setFilter(httpLogFilter);
        registration.addUrlPatterns(new String[]{"/*"});
        registration.setOrder(3);
        return registration;
    }

}
